<template>
    <div class='app-wrapper'>
        <div class='register-box'>
            <el-tabs type="border-card">
                <el-tab-pane label="基本信息修改">
                    <h3>企业信息设置</h3>
                    <el-form :model='registerForm' status-icon :rules='rules' ref='registerForm' class='login-form'>
                        <!--  <el-form-item prop="swoptions" label="所属商务部门">
                            <div class="sub-title">输入关键字后可选择补全信息</div>
                            <el-autocomplete
                              type="text"
                              class="inline-input"
                              v-model="registerForm.swoptions"
                              :fetch-suggestions="querySearchSWAsync"
                              :trigger-on-focus="false"
                              @select="handleSWSelect"
                              @input="changeSW"
                              prop="swoptions"
                              placeholder="请填写完整的所属商务部门名称">
                            </el-autocomplete>
                          </el-form-item>-->
                        <el-form-item prop="jcname" label="企业简称">
                            <el-input v-model="registerForm.jcname" :maxlength="8" placeholder="请填写正确的企业简称"></el-input>
                        </el-form-item>
                        <el-form-item prop='address' label='办公地址'>
                            <el-input v-model='registerForm.address' placeholder='请填写办公地址'></el-input>
                        </el-form-item>
                        <el-form-item prop="contactname" label="企业联系人">
                            <el-input v-model="registerForm.contactname" placeholder="请指定订单业务联系人"></el-input>
                        </el-form-item>
                        <el-form-item prop='contact' label='企业联系电话'>
                            <el-input v-model='registerForm.contact' placeholder='请填写企业联系电话'></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type='primary' @click="submitForm('registerForm')" :loading='loading'
                                       style='width:100%'>提交
                            </el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="登录密码修改">
                    <h3>修改登录密码</h3>
                    <el-form :model='passwordForm' status-icon :rules='rules' ref='passwordForm' class='login-form'>
                        <el-form-item prop='passwordOld' label='请填写旧密码'>
                            <el-input type='password' v-model='passwordForm.passwordOld'></el-input>
                        </el-form-item>
                        <el-form-item prop='password1' label='请填写密码'>
                            <el-input type='password' v-model='passwordForm.password1'></el-input>
                        </el-form-item>
                        <el-form-item prop='password2' label='确认密码'>
                            <el-input type='password' v-model='passwordForm.password2'></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type='primary' @click="submitPassForm('passwordForm')" :loading='loading'
                                       style='width:100%'>提交
                            </el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>
<script>
    import {
        getSSoptions,
        changeUser,
        getUserInfo,
        changePass,
    } from '@/api/register';
    import {removeToken} from '@/utils/auth';

    export default {
        data() {
            var validateSW = (rule, value, callback) => {
                if (this.swCode == '') {
                    callback(new Error('请输入正确的企业商务管理部门信息'));
                } else {
                    callback();
                }
            };
            var validPass = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请输入正确的密码'));
                } else {
                    if (value != this.passwordForm.password1) {
                        callback(new Error('请输入正确的密码'));
                    } else {
                        callback();
                    }
                }
            };

            return {
                wHeight: 0,
                swCode: '',
                swFlag: false,
                registerForm: {
                    swoptions: '',
                    jcname: '',
                    address: '',
                    contactname: '',
                    contact: ''
                },
                companyName:'',
                passwordForm: {
                    passwordOld: '',
                    password1: '',
                    password2: ''
                },
                list: [],
                rules: {
                    swoptions: [
                        {required: true, validator: validateSW, trigger: 'change'}
                    ],
                    jcname: [
                        {
                            required: true,
                            min: 2,
                            max: 8,
                            message: '请输入企业简称（2-8个字符）',
                            trigger: 'blur'
                        }
                    ],
                    passwordOld: [
                        {
                            required: true,
                            min: 6,
                            max: 24,
                            message: '请设置正确的旧密码',
                            trigger: 'blur'
                        }
                    ],
                    password1: [
                        {
                            required: true,
                            min: 6,
                            max: 24,
                            message: '请设置登录密码,长度在6-24个字符',
                            trigger: 'blur'
                        }
                    ],
                    password2: [{required: true, validator: validPass, trigger: 'blur'}],
                },
                loading: false
            };
        },
        created() {
            let that = this;
            //读取企业信息
            that.loading = true;
            getUserInfo()
                .then(data => {
                    that.loading = false;
                    var myData = data.data;
                    var b = JSON.stringify(myData);
                    if (b === '"{}"') {
                        that.$message.error('企业信息读取失败!');
                    } else {
                        // myData = JSON.stringify(myData); //转化为JSON字符串
                        console.log('date ', data);
                        that.registerForm.jcname = myData.companyInfo.companyName;
                        that.registerForm.address = myData.companyInfo.address;
                        that.registerForm.contactname = myData.companyInfo.contactsName;
                        that.registerForm.contact = myData.companyInfo.contactsPhone;
                        // myData = JSON.stringify(myData); //转化为JSON字符串
                        for (let i of myData.goverCompanyList) {
                            var typeId = i.departmentTypeId;
                            if (typeId == 'M812020') {
                                //商务局
                                that.registerForm.swoptions = i.departmentName;
                                that.swCode = i.departmentId;
                                that.swFlag = true;
                            }
                        }
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    that.loading = false;
                });
        },
        mounted(){
            if(localStorage.getItem('UserInfo')){
                let info = JSON.parse(localStorage.getItem('UserInfo'));
                this.companyName = info.companyNameCN;

            }
        },
        methods: {
            updateCompanyName(){
                if(!this.companyName){
                    this.$notify.error({
                        title: '错误',
                        message: '请输入企业全称'
                    });
                    return;
                }else{
                    changeCompanyName(this.companyName).then(res=>{
                        if(res.code ==0){
                            this.$message({
                                message: '企业名称更改成功',
                                type: 'success'
                            })

                        }else{
                            this.$message.error(res.msg)
                        }
                    }).catch(err=>{
                        this.$message.error(err)
                    })
                }
            },
            submitForm(formName) {
                let that = this;
                var bFlag = true;
                //
                // if (!that.swFlag || that.swCode == '') {
                //     that.$message.error('请输入正确的企业商务管理机构信息！');
                //     bFlag = false;
                // }
                if (bFlag == true) {
                    that.loading = true;
                    that.$refs[formName].validate(valid => {
                        if (valid) {
                            //注册
                            changeUser(
                                that.registerForm.jcname,
                                that.swCode,
                                that.registerForm.address,
                                that.registerForm.contactname,
                                that.registerForm.contact
                            )
                                .then(data => {
                                    that.loading = false;
                                    console.log('修改成功', data);
                                    //清除缓存资料
                                    that.$message(
                                        {
                                            type:'success',
                                            message:'企业信息修改成功，请用负责人手机号重新登录系统!'
                                        }
                                    );
                                    this.$router.push({path: '/'});
                                })
                                .catch(function (error) {
                                    console.log(error);
                                    that.loading = false;
                                });
                        } else {
                            that.loading = false;
                            that.$message.error('数据输入错误，请核对！');
                        }
                    });
                }
            },
            submitPassForm(formName) {
                let that = this;
                that.loading = true;
                that.$refs[formName].validate(valid => {
                    if (valid) {
                        //注册
                        changePass(that.passwordForm.passwordOld, that.passwordForm.password1)
                            .then(data => {
                                that.loading = false;
                                console.log('修改成功', data);
                                //清除缓存资料
                                that.$message({
                                    message: '密码修改成功，请用新密码重新登录系统！',
                                    type: 'success'
                                });
                                removeToken();
                                that.$router.push({path: '/login'});
                            })
                            .catch(function (error) {
                                console.log(error);
                                that.loading = false;
                            });
                    } else {
                        that.loading=false;
                        that.$message.error('数据输入错误，请核对！');
                    }
                });
            },
            handleSWSelect(value) {
                let that = this;
                that.swCode = value.key;
                that.swFlag = true;
            },
            changeSW() {
                let that = this;
                if (that.swFlag) {
                    that.swCode = '';
                    that.swFlag = false;
                }
            },
            //callback 回调函数,将处理好的数据推回
            querySearchSWAsync(queryString, callback) {
                let that = this;
                that.list = [];
                //计算输入字符串长度
                var l = queryString.length;
                var blen = 0;
                var i = 0;
                for (i = 0; i < l; i++) {
                    if ((queryString.charCodeAt(i) & 0xff00) != 0) {
                        blen++;
                    }
                    blen++;
                }
                //从后台获取到对象数组
                if (blen >= 2) {
                    getSSoptions(queryString)
                        .then(data => {
                            that.loading = false;
                            //在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
                            var myData = data.data;
                            if (myData.length > 0) {
                                for (let i of myData) {
                                    var map = {};
                                    map.value = i.departmentName; //将想要展示的数据作为value
                                    map.key = i.id;
                                    that.list.push(map);
                                }
                                callback(that.list);
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            that.loading = false;
                        });
                }
            }
        }
    };
</script>
<style rel='stylesheet/scss' lang='scss' scoped>
    @import 'src/styles/mixin.scss';

    .app-wrapper {
        @include clearfix;
        width: 100%;
    }

    .register-box {
        background: #fff;
        width: 500px;
        margin: auto;
        padding: 20px 30px;
        border-radius: 6px;

        h3 {
            text-align: center;
        }
    }

    .el-autocomplete {
        width: 100%;
    }

    .el-cascader {
        width: 100%;
    }
</style>
